<template>
  <div class="min-h-screen bg-gray-50 p-5 max-w-6xl mx-auto">
    <div class="mb-8">
      <div class="bg-gradient-to-br from-indigo-500 to-purple-600 text-white rounded-xl p-6">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2 text-xl font-semibold">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd"
                d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"
                clip-rule="evenodd"></path>
            </svg>
            历史记录
          </div>
        </div>
        <div class="mt-5">
          <p class="text-sm opacity-90">查看您的检测历史记录</p>
        </div>
      </div>
    </div>

    <div class="mt-5">
      <Loading v-model:show="isLoading" description="加载中...">
        <div class="bg-white rounded-lg shadow-sm">
          <div class="p-6 border-b border-gray-200">
            <div class="flex items-center gap-2 font-semibold text-gray-800">
              <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd"
                  d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z"
                  clip-rule="evenodd"></path>
              </svg>
              检测记录
            </div>
          </div>

          <div class="p-5">
            <!-- 检测记录表格：展示每次检测的编号、项目、时间与状态 -->
            <div class="overflow-x-auto">
              <table class="min-w-full divide-y divide-gray-200 text-sm">
                <thead class="bg-gray-50">
                  <tr>
                    <th class="px-4 py-3 text-left font-medium text-gray-700">
                      <input type="checkbox" :checked="isAllSelected" @change.stop="toggleSelectAll" />
                    </th>
                    <th class="px-4 py-3 text-left font-medium text-gray-700">检测项目</th>
                    <th class="px-4 py-3 text-left font-medium text-gray-700">检测结果</th>
                    <th class="px-4 py-3 text-left font-medium text-gray-700">堵塞比例</th>
                    <th class="px-4 py-3 text-left font-medium text-gray-700">时间</th>
                    <th class="px-4 py-3 text-left font-medium text-gray-700">操作</th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-100" v-if="displayedRecords.length > 0">
                  <!-- 行点击打开弹窗预览 -->
                  <tr v-for="item in displayedRecords" :key="item.id"
                    class="hover:bg-gray-50 transition-colors duration-200">
                    <td class="px-4 py-3">
                      <input type="checkbox" :checked="selectedIds.has(item.id)" @click.stop="toggleSelect(item.id)" />
                    </td>
                    <td class="px-4 py-3">
                      <div class="flex items-center gap-2">
                        <span class="font-medium text-gray-900">{{ item.title || '图片检测' }}</span>
                      </div>
                    </td>
                    <td class="px-4 py-3">
                      <div class="flex items-center gap-2">
                        <span :class="getDiagnosisBadgeClass(item.diagnosis)" class="px-2 py-1 rounded-full text-xs font-medium">
                          {{ item.diagnosis || '未知' }}
                        </span>
                      </div>
                    </td>
                    <td class="px-4 py-3">
                      <div v-if="item.ratio != null" class="text-center">
                        <span class="font-semibold text-blue-600">{{ (item.ratio * 100).toFixed(1) }}%</span>
                      </div>
                      <div v-else class="text-gray-400 text-center">-</div>
                    </td>
                    <td class="px-4 py-3 text-gray-500">{{ item.time }}</td>
                    <td class="px-4 py-3">
                      <!-- 关键功能：操作列新增查看按钮，移除整行点击查看 -->
                      <div class="flex items-center gap-2">
                        <button class="px-3 py-1 text-sm rounded bg-blue-500 text-white hover:bg-blue-600"
                          @click.stop="openPreview(item)">查看</button>
                        <button class="px-3 py-1 text-sm rounded bg-red-500 text-white hover:bg-red-600"
                          @click.stop="askDelete(item.id)">删除</button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 关键功能：分页控制 -->
            <div class="mt-4 flex items-center justify-between">
              <div class="text-sm text-gray-600">共 {{ filteredRecords.length }} 条，当前第 {{ currentPage }} / {{ totalPages
                }} 页</div>
              <div class="flex items-center gap-2">
                <button class="px-3 py-1 rounded border border-gray-300 hover:bg-gray-50 disabled:opacity-50"
                  :disabled="currentPage === 1" @click="prevPage">上一页</button>
                <select v-model.number="pageSize" class="rounded border border-gray-300 px-2 py-1">
                  <option :value="10">10/页</option>
                  <option :value="20">20/页</option>
                  <option :value="50">50/页</option>
                </select>
                <button class="px-3 py-1 rounded border border-gray-300 hover:bg-gray-50 disabled:opacity-50"
                  :disabled="currentPage === totalPages" @click="nextPage">下一页</button>
              </div>
            </div>

            <!-- 空状态：无记录时展示 -->
            <div class="flex flex-col items-center justify-center py-16 text-center"
              v-if="filteredRecords.length === 0">
              <svg class="w-12 h-12 text-gray-400 mb-4" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd"
                  d="M5 3a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2V5a2 2 0 00-2-2H5zm0 2h10v7h-2l-1-2H8l-1 2H5V5z"
                  clip-rule="evenodd"></path>
              </svg>
              <p class="text-gray-500">暂无历史记录</p>
            </div>

            <!-- 弹窗：显示上传时间与图片预览 -->
            <div v-if="showDialog" class="fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center p-4">
              <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
                <div class="p-4 border-b border-gray-200">
                  <div class="font-semibold text-gray-800">检测记录详情</div>
                </div>
                <div class="p-4 space-y-3">
                  <div class="text-sm text-gray-600">上传时间：{{ selectedRecord?.time }}</div>
                  <div class="w-full">
                    <img :src="selectedRecord?.image" alt="图片预览" class="max-h-64 mx-auto rounded" />
                  </div>
                </div>
                <div class="p-4 border-t border-gray-200 text-right">
                  <button class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                    @click="closePreview">关闭</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Loading>
      <!-- 关键功能：删除确认弹窗 -->
      <Dialog v-model:show="showDeleteDialog" title="确认删除" message="删除后不可恢复，是否确认删除？" @confirm="confirmDelete" />
      <!-- 关键功能：批量删除确认弹窗 -->
      <Dialog v-model:show="showBatchDeleteDialog" title="批量删除" message="将删除所选记录，是否确认？" @confirm="confirmBatchDelete" />
      <!-- 关键功能：删除过程全屏 Loading，阻止所有交互 -->
      <div v-if="isDeleting" class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-20">
        <Loading v-model:show="isDeleting" description="正在删除...">
          <div class="w-screen h-screen"></div>
        </Loading>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import request from '@/utils/request'
import { formatDate } from '@/utils/common'
import notify from '@/api/notify'
import Loading from '@/components/loading.vue'
import Dialog from '@/components/dialog.vue'

export default {
  name: 'HistoryPage',
  components: { Loading, Dialog },
  setup() {
    // 关键功能：从本地存储读取检测记录
    const records = ref([])
    const showDialog = ref(false)
    const selectedRecord = ref(null)
    const isLoading = ref(false)
    // 关键功能：删除确认与过程状态
    const showDeleteDialog = ref(false)
    const confirmDeleteId = ref(null)
    const isDeleting = ref(false)
    // 关键功能：搜索、筛选与分页状态
    const searchQuery = ref('')
    const statusFilter = ref('all')
    const currentPage = ref(1)
    const pageSize = ref(10)
    // 关键功能：批量选择与批量删除
    const selectedIds = ref(new Set())
    const showBatchDeleteDialog = ref(false)

    const loadRecords = async () => {
      // 关键功能：从后端拉取当前用户的检测历史
      isLoading.value = true
      try {
        const res = await request.get('/detection/history/list', { page: 1, pageSize: 20 })
        if (res && res.success && res.data) {
          const list = res.data.list || []
          records.value = list.map((it) => ({
            id: it.id,
            title: 'AI腺样体检测',
            originalImage: it.originalImageUrl || it.imageUrl,
            resultImage: it.resultImage,
            ratio: it.ratio,
            diagnosis: it.diagnosis,
            filename: it.filename,
            fileSize: it.fileSize,
            time: formatDate(it.detectedAt || it.createdAt || Date.now()),
            status: 'success',
            statusText: '成功',
            image: it.imageUrl
          }))
          // 关键功能：数据加载后重置分页
          currentPage.value = 1
          isLoading.value = false
          return
        }
        // 后端返回失败，提示并尝试本地回退
        notify.warning(res?.error || '加载历史记录失败')
      } catch (e) {
        // 网络错误或 400 等异常，提示并尝试本地回退
        notify.error(e?.message || '加载历史记录异常')
      }
      // 关键功能：失败时不进行本地回退，清空列表并保持分页为第一页
      records.value = []
      currentPage.value = 1
      isLoading.value = false
    }

    const deleteRecord = async (id) => {
      try {
        const res = await request.delete(`/detection/history/delete/${id}`)
        if (res && res.success) {
          records.value = records.value.filter((it) => it.id !== id)
          notify.success('删除成功')
          return
        }
        notify.warning(res?.error || '删除失败')
      } catch (e) {
        // 网络异常，不进行本地回退
      }
    }

    // 关键功能：触发删除确认弹窗
    const askDelete = (id) => {
      confirmDeleteId.value = id
      showDeleteDialog.value = true
    }

    // 关键功能：确认后执行删除并显示全屏 Loading，阻止交互
    const confirmDelete = async () => {
      showDeleteDialog.value = false
      if (!confirmDeleteId.value) return
      isDeleting.value = true
      try {
        await deleteRecord(confirmDeleteId.value)
      } finally {
        isDeleting.value = false
        confirmDeleteId.value = null
      }
    }

    // 关键功能：筛选与分页计算
    const filteredRecords = computed(() => {
      const q = searchQuery.value.trim().toLowerCase()
      return records.value.filter((it) => {
        const matchesQuery = !q || String(it.id).includes(q) || (it.title || '').toLowerCase().includes(q)
        const matchesStatus = statusFilter.value === 'all' ? true : (statusFilter.value === 'success' ? it.status === 'success' : it.status !== 'success')
        return matchesQuery && matchesStatus
      })
    })
    const totalPages = computed(() => Math.max(1, Math.ceil(filteredRecords.value.length / pageSize.value)))
    const displayedRecords = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      return filteredRecords.value.slice(start, start + pageSize.value)
    })

    // 关键功能：批量选择
    const selectedCount = computed(() => selectedIds.value.size)
    const isAllSelected = computed(() => displayedRecords.value.length > 0 && displayedRecords.value.every((it) => selectedIds.value.has(it.id)))
    const toggleSelect = (id) => {
      // 关键功能：切换单行选择状态
      if (selectedIds.value.has(id)) {
        selectedIds.value.delete(id)
      } else {
        selectedIds.value.add(id)
      }
      selectedIds.value = new Set(selectedIds.value)
    }
    const toggleSelectAll = () => {
      // 关键功能：当前页全选/取消
      if (isAllSelected.value) {
        displayedRecords.value.forEach((it) => selectedIds.value.delete(it.id))
      } else {
        displayedRecords.value.forEach((it) => selectedIds.value.add(it.id))
      }
      selectedIds.value = new Set(selectedIds.value)
    }
    const askBatchDelete = () => {
      if (selectedIds.value.size === 0) return
      showBatchDeleteDialog.value = true
    }
    const confirmBatchDelete = async () => {
      showBatchDeleteDialog.value = false
      if (selectedIds.value.size === 0) return
      isDeleting.value = true
      try {
        const ids = Array.from(selectedIds.value)
        for (const id of ids) {
          await deleteRecord(id)
        }
        selectedIds.value.clear()
        selectedIds.value = new Set()
        notify.success('批量删除完成')
      } finally {
        isDeleting.value = false
      }
    }

    // 关键功能：分页切换
    const prevPage = () => {
      if (currentPage.value > 1) currentPage.value--
    }
    const nextPage = () => {
      if (currentPage.value < totalPages.value) currentPage.value++
    }

    // 关键功能：当搜索、筛选或每页数量变化时重置到第一页
    watch([searchQuery, statusFilter, pageSize], () => {
      currentPage.value = 1
    })
    // 关键功能：当列表数据变化时清理不存在的选择项
    watch(records, () => {
      const idSet = new Set(records.value.map((it) => it.id))
      selectedIds.value.forEach((id) => {
        if (!idSet.has(id)) selectedIds.value.delete(id)
      })
      selectedIds.value = new Set(selectedIds.value)
    })

    const openPreview = (item) => {
      // 关键功能：打开弹窗预览指定记录
      selectedRecord.value = item
      showDialog.value = true
    }

    const closePreview = () => {
      showDialog.value = false
      selectedRecord.value = null
    }

    // 根据诊断结果获取样式类
    const getDiagnosisBadgeClass = (diagnosis) => {
      switch (diagnosis) {
        case '正常':
          return 'bg-green-100 text-green-800'
        case '轻微堵塞':
          return 'bg-yellow-100 text-yellow-800'
        case '堵塞严重':
          return 'bg-red-100 text-red-800'
        default:
          return 'bg-gray-100 text-gray-800'
      }
    }

    // 初始加载
    loadRecords()

    return {
      records,
      searchQuery,
      statusFilter,
      currentPage,
      pageSize,
      filteredRecords,
      displayedRecords,
      totalPages,
      selectedIds,
      selectedCount,
      isAllSelected,
      toggleSelect,
      toggleSelectAll,
      askBatchDelete,
      confirmBatchDelete,
      prevPage,
      nextPage,
      showDialog,
      selectedRecord,
      openPreview,
      closePreview,
      deleteRecord,
      getDiagnosisBadgeClass,
      isLoading,
      showDeleteDialog,
      showBatchDeleteDialog,
      askDelete,
      confirmDelete,
      isDeleting
    }
  }
}
</script>

<style scoped>
/* Tailwind CSS样式已应用，无需额外CSS */
</style>